import cv2
import mediapipe as mp
import time


class handDetector:
    def __init__(self):
        self.result = None
        self.mpHands = mp.solutions.hands
        self.hands = self.mpHands.Hands()

        # 画图
        self.mpDraw = mp.solutions.drawing_utils
        self.handLmsStyle = self.mpDraw.DrawingSpec(color=(0, 0, 255), thickness=3)  # 设置点样式
        self.handConStyle = self.mpDraw.DrawingSpec(color=(0, 255, 0), thickness=5)  # 设置线样式

    def findHands(self, img, draw=True):
        # -----------------捕获手-------------------
        imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        self.result = self.hands.process(imgRGB)
        if self.result.multi_hand_landmarks:  # 摄像头捕获到手，显示手指画线
            for handLms in self.result.multi_hand_landmarks:
                if draw:
                    self.mpDraw.draw_landmarks(img, handLms, self.mpHands.HAND_CONNECTIONS)
        return img

    def findPosition(self, img, handNo=0, personDraw=True):
        lmList = []
        if self.result.multi_hand_landmarks:
            myhand = self.result.multi_hand_landmarks[handNo]
            for i, lm in enumerate(myhand.landmark):
                h, w, c = img.shape
                cx, cy = int(lm.x * w), int(lm.y * h)
                lmList.append([i, cx, cy])
                if personDraw:
                    cv2.circle(img, (cx, cy), int(w / 50), (255, 0, 255), cv2.FILLED)
        return lmList


def main():
    pTime = 0
    cTime = 0
    cap = cv2.VideoCapture(0)
    detector = handDetector()
    while True:
        success, img = cap.read()
        img = detector.findHands(img)

        # -------------打印坐标信息-------------
        # handPoints = detector.findPosition(img)
        # for point in handPoints:
        #     i, cx, cy = point
        #     # 在此处进行进一步处理或分析，比如打印坐标信息
        #     print(f"关键点{i}的坐标：({cx}, {cy})")

        # --------------FPS显示--------------
        cTime = time.time()
        fps = 1 / (cTime - pTime)
        pTime = cTime
        cv2.putText(img, f'FPS={int(fps)}', (20, 50), cv2.FONT_HERSHEY_COMPLEX, 2, (255, 255, 255), 2)

        cv2.imshow("Image", img)
        if cv2.waitKey(1) == ord('q'):
            break


if __name__ == "__main__":
    main()
